Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow mocking of ARTPaginatedResult #1986

Merged
merged 1 commit into from
Oct 8, 2024

Conversation

umair-ably
Copy link
Contributor

@umair-ably umair-ably commented Oct 7, 2024

Allow mocking of ARTPaginatedResult by passing responsibility of property initialisation to any subclassing parties

Summary by CodeRabbit

  • New Features

    • Introduced a new initialization mechanism for the ARTPaginatedResult class, allowing for better control over object instantiation.
    • Added methods to check pagination status (hasNext, isLast, and items).
  • Bug Fixes

    • Improved error handling by enforcing proper initialization before calling certain methods, preventing misuse of the default initializer.
  • Documentation

    • Expanded comments for the init method to clarify its intended use and restrictions for subclasses.

Copy link

coderabbitai bot commented Oct 7, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The changes in this pull request involve modifications to the ARTPaginatedResult class in both the implementation and header files. A new instance variable _initializedViaInit is introduced to track the initialization state of the object, influencing method behavior based on whether the object was initialized with the default or a custom initializer. The init method is now a designated initializer, allowing instantiation but enforcing subclassing for certain methods. This structure aims to enhance control over object initialization and method usage.

Changes

File Change Summary
Source/ARTPaginatedResult.m Introduced _initializedViaInit to track initialization state. Modified init and initWithItems: methods. Added checks for _initializedViaInit in hasNext, isLast, items, first:, and next: methods.
Source/include/Ably/ARTPaginatedResult.h Changed init method from unavailable to designated initializer, allowing instantiation with restrictions. Expanded comments for clarity.

Poem

In the land of code where rabbits play,
A new state tracker came to stay.
With methods that check and rules to abide,
Our paginated friend now takes pride.
So hop along, let’s subclass and cheer,
For the changes made, we hold dear! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot temporarily deployed to staging/pull/1986/features October 7, 2024 13:35 Inactive
@umair-ably umair-ably force-pushed the make-ARTPaginatedResult-externally-creatable branch from 9cf4125 to 66accb2 Compare October 7, 2024 13:38
@github-actions github-actions bot temporarily deployed to staging/pull/1986/features October 7, 2024 13:39 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
Source/include/Ably/ARTPaginatedResult.h (1)

30-31: Approved: Enables mocking as intended, but consider additional safeguards

The changes to the init method and its associated comment effectively achieve the PR's objective of allowing mocking of ARTPaginatedResult. This improvement in testability is valuable for the project.

However, there's a potential risk of misuse if developers instantiate ARTPaginatedResult directly without subclassing. To mitigate this:

  1. Consider adding a compile-time warning or runtime assertion in the init method to further discourage direct usage.
  2. Update the class documentation to clearly state that this class is intended for subclassing, not direct instantiation.

Would you like assistance in implementing these additional safeguards?

Source/ARTPaginatedResult.m (1)

35-41: Consider marking init as a designated initializer

Since init is now publicly available and sets _initializedViaInit, consider explicitly marking it as a designated initializer. This enhances clarity and ensures proper initialization in subclasses.

🛑 Comments failed to post (1)
Source/ARTPaginatedResult.m (1)

88-116: 🛠️ Refactor suggestion

Refactor repeated exception handling into a helper method

The checks for _initializedViaInit and the associated exceptions are repeated in the methods hasNext, isLast, items, first, and next. To improve maintainability and reduce code duplication, consider extracting this logic into a helper method.

Apply this diff to create a helper method and utilize it in the relevant methods:

+ - (void)assertInitializedViaSubclass {
+     if (_initializedViaInit) {
+         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
+     }
+ }

- (BOOL)hasNext {
-     if (_initializedViaInit) {
-         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
-     }
+     [self assertInitializedViaSubclass];
      return _hasNext;
}

- (BOOL)isLast {
-     if (_initializedViaInit) {
-         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
-     }
+     [self assertInitializedViaSubclass];
      return _isLast;
}

- (NSArray<id> *)items {
-     if (_initializedViaInit) {
-         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
-     }
+     [self assertInitializedViaSubclass];
      return _items;
}

- (void)first:(void (^)(ARTPaginatedResult<id> *_Nullable result, ARTErrorInfo *_Nullable error))callback {
-     if (_initializedViaInit) {
-         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
-     }
+     [self assertInitializedViaSubclass];
     // ... rest of the method ...
}

- (void)next:(void (^)(ARTPaginatedResult<id> *_Nullable result, ARTErrorInfo *_Nullable error))callback {
-     if (_initializedViaInit) {
-         [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
-     }
+     [self assertInitializedViaSubclass];
     // ... rest of the method ...
}

Also applies to: 130-133

@github-actions github-actions bot temporarily deployed to staging/pull/1986/jazzydoc October 7, 2024 13:45 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (1)
Source/include/Ably/ARTPaginatedResult.h (1)

Line range hint 1-14: Update class documentation to reflect new initialization behavior

With the changes to the init method, it's important to update the class documentation to provide clear guidance on usage, especially regarding subclassing and thread safety. Consider adding the following information to the class documentation:

  1. Explain that this class is designed for subclassing when used in production code.
  2. Clarify the intended use of the public initializer for mocking in test scenarios.
  3. Provide guidance on how to properly subclass ARTPaginatedResult for production use.
  4. Ensure that the NS_SWIFT_SENDABLE attribute is still appropriate with the new initialization behavior, and document any thread-safety considerations.

Here's a suggested addition to the class documentation:

/**
 * Contains a page of results for message or presence history, stats, or REST presence requests. An `ARTPaginatedResult` response from a REST API paginated query is also accompanied by metadata that indicates the relative queries available to the `ARTPaginatedResult` object.
 *
 * This class is designed to be subclassed for production use. The public initializer is provided primarily for creating mock instances in test scenarios. When subclassing, ensure to override and implement all required methods and properties.
 *
 * Thread Safety: This class is marked as `NS_SWIFT_SENDABLE`. Ensure that any subclass maintains thread safety, especially when overriding methods or properties.
 */

This addition provides crucial information for developers working with this class, reducing the likelihood of misuse and clarifying its intended usage patterns.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9cf4125 and 66accb2.

📒 Files selected for processing (2)
  • Source/ARTPaginatedResult.m (5 hunks)
  • Source/include/Ably/ARTPaginatedResult.h (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
Source/include/Ably/ARTPaginatedResult.h (1)

Line range hint 1-46: Summary and Final Recommendation

The changes made to ARTPaginatedResult.h successfully enable mocking of the ARTPaginatedResult class, meeting the primary objective of the PR. However, there are several areas where the implementation could be improved:

  1. The initialization approach could be enhanced for better clarity and safety.
  2. Class documentation should be updated to reflect the new initialization behavior and provide guidance on proper usage.
  3. Consider the implications of these changes on thread safety and the NS_SWIFT_SENDABLE attribute.

While the current implementation is functional, implementing the suggested improvements would result in a more robust, clear, and maintainable API. These changes would benefit both the developers working on the Ably SDK and those using it in their applications.

Recommendation: Approve with comments. The PR meets its objective, but consider implementing the suggested improvements before merging.

Source/ARTPaginatedResult.m Outdated Show resolved Hide resolved
Source/ARTPaginatedResult.m Show resolved Hide resolved
Source/ARTPaginatedResult.m Show resolved Hide resolved
Source/ARTPaginatedResult.m Outdated Show resolved Hide resolved
@umair-ably umair-ably force-pushed the make-ARTPaginatedResult-externally-creatable branch from 66accb2 to 61d9c11 Compare October 7, 2024 14:58
@github-actions github-actions bot temporarily deployed to staging/pull/1986/features October 7, 2024 14:59 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
Source/ARTPaginatedResult.m (1)

87-88: Use appropriate exception type and include method name in exception message

The method initializedViaInitCheck currently raises an NSInvalidArgumentException with a fixed message. It's more appropriate to use NSInternalInconsistencyException, and including the method name in the exception message will provide more clarity about which method needs to be overridden.

Apply this diff to improve the exception:

-        [NSException raise:NSInvalidArgumentException format:@"When initializing this class using -init, you need to override this method in a subclass"];
+        [NSException raise:NSInternalInconsistencyException format:@"You must override %@ in a subclass when initializing this class using -init", NSStringFromSelector(_cmd)];
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 66accb2 and 61d9c11.

📒 Files selected for processing (2)
  • Source/ARTPaginatedResult.m (5 hunks)
  • Source/include/Ably/ARTPaginatedResult.h (1 hunks)
🧰 Additional context used

Source/include/Ably/ARTPaginatedResult.h Outdated Show resolved Hide resolved
@github-actions github-actions bot temporarily deployed to staging/pull/1986/jazzydoc October 7, 2024 15:04 Inactive
@lawrence-forooghian
Copy link
Collaborator

@umair-ably please can you change it so that I am not listed as the commit's sole author? It gives the impression that I wrote all of the code that's in here, which I didn't (e.g. initializedViaInitCheck). My preference would be for you to change the author to be you (since you wrote the commit message) and to add me as a co-author.

@lawrence-forooghian
Copy link
Collaborator

Allow mocking of ARTPaginatedResult by passing responsibility of property initialisation to any subclassing parties

This commit message isn't quite right. The base class remains responsible for initialising its own properties. A more accurate description would be "by allowing it to be subclassed by a user of the SDK".

Source/include/Ably/ARTPaginatedResult.h Outdated Show resolved Hide resolved
Source/include/Ably/ARTPaginatedResult.h Outdated Show resolved Hide resolved
Source/ARTPaginatedResult.m Outdated Show resolved Hide resolved
Source/include/Ably/ARTPaginatedResult.h Outdated Show resolved Hide resolved
@umair-ably umair-ably force-pushed the make-ARTPaginatedResult-externally-creatable branch from 61d9c11 to ca4e4cb Compare October 7, 2024 20:48
@github-actions github-actions bot temporarily deployed to staging/pull/1986/features October 7, 2024 20:49 Inactive
@umair-ably
Copy link
Contributor Author

@coderabbitai pause

@github-actions github-actions bot temporarily deployed to staging/pull/1986/jazzydoc October 7, 2024 20:52 Inactive
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
Source/include/Ably/ARTPaginatedResult.h (1)

29-30: Good improvements, consider additional enhancements for clarity and safety

The changes align well with the PR objective of enabling mocking for ARTPaginatedResult. The added documentation clearly explains the limitations and intended use, and the use of NS_DESIGNATED_INITIALIZER is a good improvement. However, to further enhance the API's clarity and safety, consider the following suggestions:

  1. Use the NS_SWIFT_UNAVAILABLE macro to prevent unintended usage in Swift:
- (instancetype)init NS_DESIGNATED_INITIALIZER NS_SWIFT_UNAVAILABLE("Use a subclass for creating mock instances in tests");
  1. Add a class method for creating mock instances, making the testing purpose more explicit:
+ (instancetype)mockForTesting;

These changes would provide a clearer API for both production and testing use cases while maintaining the desired flexibility for mocking and adding an extra layer of safety.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 61d9c11 and ca4e4cb.

📒 Files selected for processing (2)
  • Source/ARTPaginatedResult.m (5 hunks)
  • Source/include/Ably/ARTPaginatedResult.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Source/ARTPaginatedResult.m
🧰 Additional context used

Copy link

coderabbitai bot commented Oct 7, 2024

✅ Actions performed

Reviews paused.

…y a user of the SDK

Co-authored-by: Lawrence Forooghian <[email protected]>
@umair-ably
Copy link
Contributor Author

@coderabbitai pause

Copy link

coderabbitai bot commented Oct 7, 2024

✅ Actions performed

Reviews paused.

@umair-ably umair-ably merged commit ccca241 into main Oct 8, 2024
5 of 8 checks passed
@umair-ably umair-ably deleted the make-ARTPaginatedResult-externally-creatable branch October 8, 2024 10:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants